<?php

namespace App\Api\Http\Controllers\weixin\In;

use App\Admin\Eloquent\ProjectsUser;
use App\Api\Eloquent\GiftReceive;
use App\Api\Eloquent\Projects;
use App\Api\Eloquent\User;
use Illuminate\Http\Request;
use App\Api\Http\Controllers\Controller;
use Ibeibeili\SinaPay\Facades\CreateHostingCollectTrade;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;
use Ibeibeili\SinaPay\Facades\QueryBalance;
use App\Eloquent\TradeRecords;
use Mockery\CountValidator\Exception;
use App\Admin\Eloquent\ProfitRole;
use DB;

class BuyProjectsController extends Controller {
    /*
     * 进入买标页面
     */
    public function gotoBuyProject(Request $request,$id){
        $user=User::user();
        $params['identity_id']=$user->identity_id;
        $params['identity_type']='UID';
        $params['account_type']='SAVING_POT';
        $result=QueryBalance::send($params);
        if($result['response_code']=='NO_BASIC_ACCOUNT'){
            $data['user_money']='0.00';//余额
        }
        elseif($result['response_code']!='APPLY_SUCCESS'){
            empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
            return $this->my_jsonp($request->input('callback'),'',600,$result['response_message']);
        }
        else{
            $data['user_money']=number_format($result['available_balance'],2);//可用余额
        }
        $one=Projects::getOneProjects($id);
        if($one->count()) {
            $projects = Projects::getalltail($one);
            foreach ($projects as $key => $project) {
                $data['new_project']=false;
                if($project->new_projects==1){
                    if(ProjectsUser::where('user_id','=',$user->id)->exists()){
                        $data['new_project']=true;
                    }
                }
                $profit_rule = ProfitRole::where('profit_id', $project->profits_cate)//分润id
                ->where('role', 'User')//投资人
                ->sum('scale');
                $profit_rule_cate = $project->finance_time_cate == 'mm' ? '12' : '360';
//                $data['profit_rule'] =$profit_rule*floor(10000 / $profit_rule_cate)/100;//计算利率
                $data['profit_rule'] =$profit_rule / $profit_rule_cate;//计算利率
                $data['profit_rule_year'] = $profit_rule;//年化利率
                if ($project->finance_time_cate == 'm') {
                    $data['profit_rule_num'] = $project->finance_time_num * 30;
                } else {
                    $data['profit_rule_num'] = $project->finance_time_num;
                }
                $data['profit_rule_r_num'] = $project->finance_time_num;
                $data['profit_rule_cate'] = $project->r_finance_time_cate;
                $data['need_money'] = $project->need_money;//可投金额
                $data['r_need_money'] = $project->r_need_money;//
                //最低金额
                if ($project->r_need_money < $project->finance_rule_money_r && $project->r_need_money > 0) {
                    $data['finance_rule_money'] = $project->r_need_money;
                } else {
                    $data['finance_rule_money'] = $project->finance_rule_money_r;
                }
                $data['title'] = $project->projects_name;
                $data['status'] = $project->status;
                $data['id'] = $project->id;
            }
        }
        return $this->my_jsonp($request->input('callback'),compact('data'));
    }
    /*
     * 发起购标请求
     */
    public function buyProjects(Request $request){
        $data=$request->UserData;
        $validator=Validator::make($data,[
            'money'=>'numeric',
            ],[
            'numeric'=>'金额格式有误',
        ]);
        if($validator->fails()){
            $v_message=$validator->errors();
            if($v_message->has('money')){
                return $this->my_jsonp($request->input('callback'),'',899,'投资金额必须为正整数');
            }
        }
            $user=User::user();
            if($user->userInfo->name_verified==0){
                return $this->my_jsonp($request->input('callback'),'',411);//411请先实名认证
            }
            if($user->phone_number_verified==0){
                return $this->my_jsonp($request->input('callback'),'',412);//412请先绑定手机
            }
            if($user->userInfo->bank_card_id==null){
                return $this->my_jsonp($request->input('callback'),'',413);//413请先绑定银行卡
            }
            if($data['money']<=0 || floor($data['money'])!=$data['money']){
                return $this->my_jsonp($request->input('callback'),'',899,'投资金额必须为正整数');
            }
            $data['money']=floor($data['money']);
            $projects=Projects::getOneProjects($data['projectsId']);

            foreach($projects as $item){
                if($item->new_projects==1){
                    if(ProjectsUser::where('user_id','=',$user->id)->exists()){
                        return $this->my_jsonp($request->input('callback'),'',600,'您无法再投资新手标');
                    }
                }
                if($data['money']>($item->finance_money-$item->financed_money)){
                    return $this->my_jsonp($request->input('callback'),'',600,'最多投资'.$item->finance_money-$item->financed_money);
                }
            }
            $params['identity_id']=$user->identity_id;
            $params['identity_type']='UID';
            $params['account_type']='SAVING_POT';
            $result=QueryBalance::send($params);
            if($result['response_code']=='NO_BASIC_ACCOUNT'){
                return $this->my_jsonp($request->input('callback'),'',414);
            }elseif($result['response_code']!='APPLY_SUCCESS'){
                empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
                return $this->my_jsonp($request->input('callback'),'',600,$result['response_message']);
            }
            if($data['money']>$result['available_balance']){
                return $this->my_jsonp($request->input('callback'),'',414);
            }
            foreach($projects as $project){

                //选择可用红包(该项目是否可使用红包，是否可累计使用红包,满足使用规则的红包)
                if($project->gift_check==1){//可以使用红包
                    $choose_cate=$project->gift_money_auto;//是否可以累计使用红包(多选框or单选框)
                    $user_gift=\App\Eloquent\Projects::getGift($data['money'],$project->id,$user->id);
//                    $user_gift=GiftReceive::join('gift_activities','gift_activities.id','=','gift_receives.activity_id')
//                        ->where('gift_receives.user_id','=',$user->id)
//                        ->where('gift_activities.used_rule_money','<=',$data['money'])//满足使用规则金额
//                        ->where('gift_receives.end_time','>',date('Y-m-d H:i:s'))//未结束
//                        ->whereNull('gift_receives.use_time')//未使用
//                        ->where('gift_receives.status','=','0')
//                        ->where('gift_receives.activity_type','=','gift_activity_type_1')//为投资红包
//                        ->select('gift_activities.cate_id','gift_activities.name','gift_receives.*')
//                        ->get();
                    if($project->gift_cate!=0){
                        $user_gift=$user_gift->where('cate_id','=',$project->gift_cate)->orWhere('cate_id','=','0');//该用户所有项目可用的红包
                    }
//                    if($project->finance_time_cate=='d'){
//                        $user_gift=$user_gift->where('cate_id','<>','gift_activity_cate_register');//该用户所有项目可用的红包
//                    }
                    $user_can_gift=$user_gift;
                    if($user_can_gift->count()!=0){
                        Cache::put('api_trade_gift'.$user->id,$user_can_gift,5);
                    }
                    $user_trade_money=$data['money'];
                    Cache::put('api_user_trade_money'.$user->id,$user_trade_money,5);
                    return $this->my_jsonp($request->input('callback'),compact('user_can_gift','choose_cate'));
                }
                $user_trade_money=$data['money'];
                Cache::put('api_user_trade_money'.$user->id,$user_trade_money,5);
                return $this->my_jsonp($request->input('callback'));
            }
        return $this->my_jsonp($request->input('callback'),'',600,'投资出错啦,稍等一下吧.');
    }
    /*
     * 发起新浪代付请求
     */
    public function launchSinaTrade(Request $request){
        $data['gift_array']=$request->gift_array;
        $data['projectsId']=$request->projectsId;
        $user=User::user();
        $data['money']=Cache::get('api_user_trade_money'.$user->id);
        $data['money']=floor($data['money']);
            try {
                DB::beginTransaction();
                $user_use_gift=array();
                $gift_money=0;
                if(isset($data['gift_array'])){
                    $user_gift_data=Cache::get('api_trade_gift'.$user->id);
                    if(!empty($user_gift_data)){
                        if($data['gift_array']!=''){
                            $data['gift_array']=explode(',',$data['gift_array']);
                            //红包索引数组
                            foreach($data['gift_array'] as $key=>$gift){
                                $gift_id[]=$user_gift_data[$gift]->id;
                                $gift_money=$user_gift_data[$gift]->money+$gift_money;
                                $user_use_gift[]=$user_gift_data[$gift];
                            }
                            if(!GiftReceive::verifStatus($gift_id,0)){
                                throw new Exception('有红包状态不正常',805);//有红包状态不正常
                            }
                        }
                    }
                }
                $r_project=Projects::getOneProjects($data['projectsId']);
                $R_project=Projects::getalltail($r_project);
                foreach($R_project as $project ){
                    if($project->new_projects==1){
                        if(ProjectsUser::where('user_id','=',$user->id)->exists()){
                            throw new Exception('您无法再投资新手标',600);//您无法再投资新手标
                        }
                    }
                    //金额是否为项目起投金额倍数
                    if($project->finance_rule_fold==1 && $data['money']%$project->finance_rule_money!=0){
                        throw new Exception('金额不为项目起投金额倍数',804);
                    }
                    if(($project->r_need_money)>($project->finance_rule_money_r)){
                        //可投金额大于等于项目起投金额
                        if($data['money']<$project->finance_rule_money_r){
                            throw new Exception('金额需大于等于项目起投金额',802);
                        }
                        if($data['money']+$gift_money>$project->r_need_money){
                            throw new Exception('金额需小于等于项目可投金额',801);
                        }
                    }
                    else{
                        if($data['money']<$project->r_need_money ){
                            throw new Exception('金额需大于等于项目起投金额',802);
                        }
                        if($data['money']+$gift_money>$project->r_need_money){
                            throw new Exception('或者总金额需小于等于项目可投金额',801);
                        }
                    }
                    //金额小于等于用户可用余额
                    $params['identity_id']=$user->identity_id;
                    $params['identity_type']='UID';
                    $params['account_type']='SAVING_POT';
                    $result=QueryBalance::send($params);
                    //没有存钱罐账户
                    if($result['response_code']=='NO_BASIC_ACCOUNT'){
                        throw new Exception('余额不足',414);
                    }elseif($result['response_code']!='APPLY_SUCCESS'){
                        empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
                        throw new Exception($result['response_message'],600);
                    }
                    //余额不足
                    if($data['money']>$result['available_balance']){
                        throw new Exception('余额不足',414);
                    }
                    //创建托管代收交易
                    $sn=createSn();
                    $remarks='用户投资';
                    $sina_data=[
                        'out_trade_no'=>$sn,
                        'out_trade_code'=>'1001',
                        'summary'=>$remarks,
                        'payer_id'=>$user->identity_id,
                        'payer_identity_type'=>'UID',
//                        'amount'=>$data['money'],
                        'pay_method'=>'online_bank^'.$data['money'].'^SINAPAY,DEBIT,C',
                        'collect_trade_type'=>'pre_auth',
                        'return_url'=>$this->getNowUrl().'/weixin/html/Ucenter/U-MyProjects.html',
                    ];
                    //新增交易流水记录
                    $records=new TradeRecords([
                        'type'=>2,
                        'project_id'=>$project->id,
                        'sn'=>$sn,
                        'pay_user'=>$user->id,
                        'remarks'=>$remarks,
                        'receive_user'=>$project->financier_id,
                        'money'=>$data['money'],
                        'created_at'=>date('Y-m-d H:i:s'),
                    ]);
                    $records->save();
                    //使用项目的投资红包
                    if(!empty($user_use_gift)){
                        foreach ($user_use_gift as $item) {
                            $sn=createSn();
                            $remarks='使用红包投资项目';
                            TradeRecords::insert([
                                'type'=>7,
                                'project_id'=>$project->id,
                                'sn'=>$sn,
                                'pay_user'=>$user->id,
                                'receive_user'=>$project->financier_id,
                                'money'=>$item->money,
                                'created_at'=>date('Y-m-d H:i:s'),
                                'remarks'=>$remarks,
                                'gift'=>$item->id,
                                'pid'=>$records->id,
                            ]);
                        }
                    }
                }
                DB::commit();
                return CreateHostingCollectTrade::send($sina_data);
            } catch (\Exception $e) {
                DB::rollback();
                $code=array('805','414','600','804','802','801');
                if(in_array($e->getCode(),$code)){
                    $message=$e->getMessage();
                }else{
                    $message='系统错误';
                }
                return view('api.weixin.form_list',compact('message'));

            }

    }
}